package com.css.zfzx.sjcj.modules.hddcA6StationHasWaveforms.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.constants.PlatformConstants;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.PlatformDateUtils;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.bpm.platform.utils.UUIDGenerator;
import com.css.zfzx.sjcj.common.excel.handler.ActiveFaultVerifyBaseHandler;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcA6StationHasWaveforms.repository.HddcA6StationhaswaveformsNativeRepository;
import com.css.zfzx.sjcj.modules.hddcA6StationHasWaveforms.repository.HddcA6StationhaswaveformsRepository;
import com.css.zfzx.sjcj.modules.hddcA6StationHasWaveforms.repository.entity.HddcA6StationhaswaveformsEntity;
import com.css.zfzx.sjcj.modules.hddcA6StationHasWaveforms.service.HddcA6StationhaswaveformsService;
import com.css.zfzx.sjcj.modules.hddcA6StationHasWaveforms.viewobjects.HddcA6StationhaswaveformsPageVO;
import com.css.zfzx.sjcj.modules.hddcA6StationHasWaveforms.viewobjects.HddcA6StationhaswaveformsQueryParams;
import com.css.zfzx.sjcj.modules.hddcA6StationHasWaveforms.viewobjects.HddcA6StationhaswaveformsVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author zyb
 * @date 2020-11-28
 */
@Service
public class HddcA6StationhaswaveformsServiceImpl implements HddcA6StationhaswaveformsService {

    private final HddcA6StationhaswaveformsRepository hddcA6StationhaswaveformsRepository;
    private final HddcA6StationhaswaveformsNativeRepository hddcA6StationhaswaveformsNativeRepository;
    private final ActiveFaultVerifyBaseHandler activeFaultVerifyBaseHandler;

    @Autowired
    public HddcA6StationhaswaveformsServiceImpl(HddcA6StationhaswaveformsRepository hddcA6StationhaswaveformsRepository,
                                                HddcA6StationhaswaveformsNativeRepository hddcA6StationhaswaveformsNativeRepository,
                                                ActiveFaultVerifyBaseHandler activeFaultVerifyBaseHandler) {
        this.hddcA6StationhaswaveformsRepository = hddcA6StationhaswaveformsRepository;
        this.hddcA6StationhaswaveformsNativeRepository = hddcA6StationhaswaveformsNativeRepository;
        this.activeFaultVerifyBaseHandler = activeFaultVerifyBaseHandler;
    }

    @Override
    public JSONObject queryHddcA6Stationhaswaveformss(HddcA6StationhaswaveformsQueryParams queryParams, int curPage, int pageSize, String sort, String order) {
        Page<HddcA6StationhaswaveformsPageVO> hddcA6StationhaswaveformsPage = this.hddcA6StationhaswaveformsNativeRepository.queryHddcA6Stationhaswaveformss(queryParams, curPage, pageSize, sort, order);
        return PlatformPageUtils.formatPageData(hddcA6StationhaswaveformsPage);
    }

    @Override
    public HddcA6StationhaswaveformsEntity getHddcA6Stationhaswaveforms(String id) {
        return this.hddcA6StationhaswaveformsRepository.findById(id).orElse(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcA6StationhaswaveformsEntity saveHddcA6Stationhaswaveforms(HddcA6StationhaswaveformsEntity hddcA6Stationhaswaveforms) {
        String uuid = UUIDGenerator.getUUID();
        hddcA6Stationhaswaveforms.setUuid(uuid);
        hddcA6Stationhaswaveforms.setCreateUser(PlatformSessionUtils.getUserId());
        Timestamp now = PlatformDateUtils.getCurrentTimestamp();
        hddcA6Stationhaswaveforms.setCreateTime(now);
        hddcA6Stationhaswaveforms.setUpdateTime(now);
        hddcA6Stationhaswaveforms.setIsValid(PlatformConstants.Y);
        hddcA6Stationhaswaveforms.setQualityinspectionStatus(PlatformConstants.N);
        hddcA6Stationhaswaveforms.setExtends10(PlatformConstants.Y);
        this.hddcA6StationhaswaveformsRepository.save(hddcA6Stationhaswaveforms);
        return hddcA6Stationhaswaveforms;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcA6StationhaswaveformsEntity updateHddcA6Stationhaswaveforms(HddcA6StationhaswaveformsEntity hddcA6Stationhaswaveforms) {
        HddcA6StationhaswaveformsEntity entity = hddcA6StationhaswaveformsRepository.findById(hddcA6Stationhaswaveforms.getUuid()).get();
        UpdateUtil.copyNullProperties(entity, hddcA6Stationhaswaveforms);
        hddcA6Stationhaswaveforms.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcA6Stationhaswaveforms.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcA6StationhaswaveformsRepository.save(hddcA6Stationhaswaveforms);
        return hddcA6Stationhaswaveforms;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcA6Stationhaswaveformss(List<String> ids) {
        List<HddcA6StationhaswaveformsEntity> hddcA6StationhaswaveformsList = this.hddcA6StationhaswaveformsRepository.findAllById(ids);
        if (!PlatformObjectUtils.isEmpty(hddcA6StationhaswaveformsList) && hddcA6StationhaswaveformsList.size() > 0) {
            for (HddcA6StationhaswaveformsEntity hddcA6Stationhaswaveforms : hddcA6StationhaswaveformsList) {
//                this.hddcA6StationhaswaveformsRepository.delete(hddcA6Stationhaswaveforms);
                hddcA6Stationhaswaveforms.setIsValid(PlatformConstants.N);
                hddcA6Stationhaswaveforms.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcA6Stationhaswaveforms.setUpdateTime(new Date());
                this.hddcA6StationhaswaveformsRepository.save(hddcA6Stationhaswaveforms);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        return PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
    }

    @Override
    public void exportFile(HddcA6StationhaswaveformsQueryParams queryParams, HttpServletResponse response) {
        List<HddcA6StationhaswaveformsEntity> yhDisasterEntities = hddcA6StationhaswaveformsNativeRepository.exportYhDisasters(queryParams);
        List<HddcA6StationhaswaveformsVO> list = new ArrayList<>();
        for (HddcA6StationhaswaveformsEntity entity : yhDisasterEntities) {
            HddcA6StationhaswaveformsVO yhDisasterVO = new HddcA6StationhaswaveformsVO();
            BeanUtils.copyProperties(entity, yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "台站与小震波形数据关联表", "台站与小震波形数据关联表", HddcA6StationhaswaveformsVO.class, "台站与小震波形数据关联表.xls", response);
    }

    @Override
    public String importExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            params.setVerifyHandler(activeFaultVerifyBaseHandler);
            // 获取到Excel数据
            ExcelImportResult<HddcA6StationhaswaveformsVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcA6StationhaswaveformsVO.class, params);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                for (HddcA6StationhaswaveformsVO yhDisasterVO : result.getFailList()) {
                    returnMsg.append("第").append(yhDisasterVO.getRowNum()).append("行").append(yhDisasterVO.getErrorMsg()).append("<br/>");
                }
                if (returnMsg.length() > 0)
                    return returnMsg.toString();
            }
            List<HddcA6StationhaswaveformsVO> list = result.getList();
            //保存
            saveDisasterList(list);
            return returnMsg.append("成功导入").append(result.getList().size()).toString();
        } catch (Exception e) {
            return "导入失败，请检查数据正确性";
        }
    }

    /**
     * 批量存入库表并且返回错误数量
     */
    public void saveDisasterList(List<HddcA6StationhaswaveformsVO> list) {
        for (HddcA6StationhaswaveformsVO hddcA6StationhaswaveformsVO : list) {
            HddcA6StationhaswaveformsEntity yhDisasterEntity = new HddcA6StationhaswaveformsEntity();
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(hddcA6StationhaswaveformsVO, yhDisasterEntity);
            saveHddcA6Stationhaswaveforms(yhDisasterEntity);
        }
    }

    /**
     * 逻辑删除-根据项目id删除数据
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcA6StationhaswaveformsEntity> hddcA1InvrgnhasmaterialtableList = this.hddcA6StationhaswaveformsRepository.queryByProjectId(projectIds);
        if (!PlatformObjectUtils.isEmpty(hddcA1InvrgnhasmaterialtableList) && hddcA1InvrgnhasmaterialtableList.size() > 0) {
            for (HddcA6StationhaswaveformsEntity hddcA1Invrgnhasmaterialtable : hddcA1InvrgnhasmaterialtableList) {
                hddcA1Invrgnhasmaterialtable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcA1Invrgnhasmaterialtable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcA1Invrgnhasmaterialtable.setIsValid("0");
                this.hddcA6StationhaswaveformsRepository.save(hddcA1Invrgnhasmaterialtable);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     */
    @Override
    public void deleteByTaskId(List<String> taskId) {
        List<HddcA6StationhaswaveformsEntity> hddcA1InvrgnhasmaterialtableList = this.hddcA6StationhaswaveformsRepository.queryByTaskId(taskId);
        if (!PlatformObjectUtils.isEmpty(hddcA1InvrgnhasmaterialtableList) && hddcA1InvrgnhasmaterialtableList.size() > 0) {
            for (HddcA6StationhaswaveformsEntity hddcA1Invrgnhasmaterialtable : hddcA1InvrgnhasmaterialtableList) {
                hddcA1Invrgnhasmaterialtable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcA1Invrgnhasmaterialtable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcA1Invrgnhasmaterialtable.setIsValid("0");
                this.hddcA6StationhaswaveformsRepository.save(hddcA1Invrgnhasmaterialtable);
            }
        }
    }

}
